<template>
  <div v-if="type === 'image'">
    <div>
      <ul class="el-upload-list el-upload-list--picture-card">
        <li tabindex="0" v-for="(pic, index) in pickItem" class="el-upload-list__item is-ready" :style="'width: ' + width + 'px;height: ' + height + 'px'">
          <div>
            <img :src="pic.imgUrl" alt="" class="el-upload-list__item-thumbnail" />
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-delete" @click="deleteMaterial(index)">
                <el-icon><DeleteFilled /></el-icon>
              </span>
            </span>
          </div>
        </li>
        <li v-if="num > 1 || pickItem.length == 0">
          <div
            tabindex="0"
            class="el-upload el-upload--picture-card"
            :style="'width: ' + width + 'px;height: ' + height + 'px;' + 'line-height:' + height + 'px;'"
            @click="toSelectMaterial()">
            <el-icon><UploadFilled /></el-icon>
          </div>
        </li>
      </ul>
    </div>
<!--    <div-->
<!--      v-else-->
<!--      tabindex="0"-->
<!--      class="el-upload el-upload&#45;&#45;picture-card"-->
<!--      :style="'width: ' + width + 'px;height: ' + height + 'px;' + 'line-height:' + height + 'px;'"-->
<!--      @click="toSelectMaterial()">-->
<!--      <el-icon><UploadFilled /></el-icon>-->
<!--    </div>-->

    <el-dialog v-model="dialogVisible" append-to-body width="35%">
      <img :src="url" alt="" style="width: 100%" />
    </el-dialog>

    <el-dialog v-model="listDialogVisible" title="图片素材库" append-to-body width="75%" height="70%">
      <el-container>
        <el-aside width="unset">
          <div style="margin-bottom: 10px">
            <el-button class="el-icon-plus" size="small" @click="materialGroupAdd()">添加分组</el-button>
          </div>
          <el-tabs v-model="materialGroupObjId" v-loading="materialGroupLoading" tab-position="left" style="height: 510px" @tab-click="tabClick">
            <el-tab-pane v-for="(item, index) in materialGroupList" :key="item.id" :name="item.name">
              <template #label>
                <span> {{ item.name }}</span>
              </template>
            </el-tab-pane>
          </el-tabs>
        </el-aside>
        <el-main>
          <el-card>
            <template #header>
              <div>
                <el-row>
                  <el-col :span="12">
                    <span>{{ materialGroupObj.name }}</span>
                    <span v-if="materialGroupObj.id !== '-1'">
                      <el-button size="small" link type="primary"  class="el-icon-edit" style="margin-left: 10px" @click="materialGroupEdit(materialGroupObj)">重命名</el-button>
                      <el-button size="small" link type="primary"  class="el-icon-delete" style="margin-left: 10px; color: red" @click="materialGroupDelete(materialGroupObj)">{{$t('button.delete')}}</el-button>
                    </span>
                  </el-col>
                  <el-col :span="12" style="text-align: right">
                    <el-upload
                      :action="uploadApi"
                      :headers="headers"
                      :file-list="[]"
                      :on-progress="handleProgress"
                      :before-upload="beforeUpload"
                      :on-success="handleSuccess"
                      :data="{ type: 1 }"
                      :limit="num"
                      multiple>
                      <el-button size="small" type="primary">批量上传</el-button>
                    </el-upload>
                  </el-col>
                </el-row>
              </div>
            </template>
            <div v-loading="tableLoading">
              <el-alert v-if="tableData.length <= 0" :title="$t('data.nodata')" type="info" :closable="false" center show-icon />
              <el-checkbox-group v-model="urls" :max="num" @change="handleCheckedChange">
                <el-row :gutter="5">
                  <el-col v-for="(item, index) in tableData" :key="index" :span="4">
                    <el-card :body-style="{ padding: '5px' }">
                      <el-tag>{{ item.fileType }}</el-tag>
                      <video
                        v-if="item.fileType === 'MP4'"
                        ref="videoPlay"
                        :src="item.imgUrl"
                        style="width: 100%; height: 100px; background-color: black"
                        :z-index="999">
                        您的浏览器不支持视频播放
                      </video>
                      <el-image
                        v-else
                        style="width: 100%; height: 100px"
                        :src="item.imgUrl"
                        fit="contain"
                        :preview-src-list="[item.imgUrl]"
                        :z-index="999"/>
                      <div>
                        <el-checkbox class="material-name" :label="item">选择</el-checkbox>
                        <el-row>
                          <el-col :span="24" class="col-do">
                            <el-button link type="primary" size="small" @click="materialDel(item)">$t('button.delete')</el-button>
                          </el-col>
                        </el-row>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
              </el-checkbox-group>
              <el-pagination
                v-model:current-page="page.pageNum"
                style="margin-top: 20px"
                :page-sizes="[12, 24]"
                :page-size="page.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
                class="pagination"
                @size-change="sizeChange"
                @current-change="pageChange"
              />
            </div>
          </el-card>
        </el-main>
      </el-container>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="small" @click="listDialogVisible = false">取 消</el-button>
          <el-button type="primary" size="small" @click="sureUrls">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { listGroup, addGroup, delGroup, updateGroup } from '@/api/shopping/material/group';
import { listMaterial, addMaterial, delMaterial, updateMaterial } from '@/api/shopping/material';
import { getToken } from '@/utils/auth';
import { propTypes } from '@/utils/propTypes.js';
import { to } from 'await-to-js';
import { useI18n } from 'vue-i18n';
const { locale, t } = useI18n();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const props = defineProps({
  // value: {
  //   type: Array,
  //   default: () => []
  // },
  imgList: {
    type: Array,
    default: () => []
  },
  type: propTypes.string.def(''),
  uploadType: propTypes.number.def(0),
  num: propTypes.number.def(5),
  width: propTypes.number.def(150),
  height: propTypes.number.def(150)
});

const headers = {
  Authorization: getToken()
};

const emit = defineEmits(['update:modelValue', 'deleteMaterial', 'handleChecked']);

const dialogVisible = ref(false);
const myValue = ref('');
const myValueCount = ref(0);
const url = ref('');
const listDialogVisible = ref(false);
const materialGroupList = ref([]);
const materialGroupObjId = ref('-1');
const materialGroupObj = ref({});
const materialGroupLoading = ref(false);
const tableData = ref([]);
const resultNumber = ref(0);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadApi = baseUrl + '/common/upload/' + props.uploadType;
const page = ref({
  total: 0, // 总页数
  pageNum: 1, // 当前页数
  pageSize: 12 // 每页显示多少条
});
const tableLoading = ref(false);
const groupId = ref('');
const urls = ref([]);
const pickItem = ref([]);

/**
 *  分组列表
 */
const materialGroupPage = () => {
  materialGroupLoading.value = true;
  listGroup().then((response) => {
    console.log('materialGroupPage ', response);
    materialGroupLoading.value = false;
    const groupList = response.rows;
    console.log('groupList', groupList);
    groupList.unshift({
      id: '-1',
      name: '全部分组'
    });
    materialGroupList.value = groupList;
    tabClick({
      index: 0
    });
  });
};

/**
 *  切换分组
 * @param tab
 */
const tabClick = (tab) => {
  urls.value = [];
  const index = Number(tab.index);
  const groupObj = materialGroupList.value[index];
  groupObj.index = index;
  materialGroupObj.value = groupObj;
  materialGroupObjId.value = groupObj.id + '';
  console.log('groupObj', groupObj);

  page.value.pageNum = 1;
  page.value.total = 0;
  if (groupObj.id !== '-1') {
    groupId.value = groupObj.id;
  } else {
    groupId.value = null;
  }
  console.log('groupId', groupId.value);
  console.log('page', page);
  getPage(page.value, {});
};

/**
 *  获取图片素材列表
 * @param page
 * @param params
 */
const getPage = (page, params) => {
  tableLoading.value = true;
  listMaterial({
    groupId: groupId.value,
    pageNum: page.pageNum, // 当前页数
    pageSize: page.pageSize // 每页显示多少条
  })
    .then((response) => {
      let data = response.rows;
      console.log('listMaterial', data);
      console.log('listMaterial response', response);
      tableData.value = data;

      page.value.total = response.total;
      page.value.pageNum = page.pageNum;
      page.value.pageSize = page.pageSize;
      tableLoading.value = false;
    })
    .catch(() => {
      tableLoading.value = false;
    });
};

/**
 *  删除图片
 */
const deleteMaterial = (index) => {
  proxy?.$modal.confirm('是否确认删除？').finally(() => {
    tableLoading.value = false;
    urls.value.splice(index, 1);
    pickItem.value.splice(index, 1);
    emit('deleteMaterial', '');
  });
  // myValue.value = '';
  // myValueCount.value = 0;
};
const toSelectMaterial = () => {
  listDialogVisible.value = true;
  if (tableData.value.length <= 0) {
    materialGroupPage();
  }
};

/**
 *  删除分组
 * @param materialGroupObj
 * @returns {Promise<void>}
 */
const materialGroupDelete = async (materialGroupObj) => {
  await proxy?.$modal.confirm('是否确认删除该分组的数据项？').finally(() => (tableLoading.value = false));
  await delGroup(materialGroupObj.id);
  proxy?.$modal.msgSuccess('删除成功');
};

const materialGroupEdit = async (materialGroupObj: any) => {
  const [err, res] = await to(
    ElMessageBox.prompt('请输入分组名', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false
    })
  );
  if (!err && res) {
    let data = {
      id: materialGroupObj.value.id,
      name: res.value
    };
    await updateGroup(data);
    proxy?.$modal.msgSuccess('修改成功');
  }
};

const materialGroupAdd = async () => {
  const [err, res] = await to(
    ElMessageBox.prompt('请输入分组名', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false
    })
  );
  if (!err && res) {
    let data = {
      name: res.value
    };
    await addGroup(data);
    proxy?.$modal.msgSuccess('添加成功');
    materialGroupPage();
  }
};

const sizeChange = (val) => {
  console.log(val);
  page.value.pageNum = 1;
  page.value.pageSize = val;
  getPage(page, {});
};

const pageChange = (val) => {
  console.log(val);
  page.value.pageNum = val;
  // this.page.pageSize = val
  getPage(page.value, {});
};

const materialRename = async (item) => {
  const [err, res] = await to(
    ElMessageBox.prompt('请输入素材名', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false
    })
  );
  if (!err && res) {
    let data = {
      name: item.value
    };
    await updateMaterial(data);
    proxy?.$modal.msgSuccess('修改成功');
    materialGroupPage();
  }
};

const materialDel = async (item) => {
  await proxy?.$modal.confirm('是否确认删除该素材？').finally(() => (tableLoading.value = false));
  await delMaterial(item.id);
  proxy?.$modal.msgSuccess('删除成功');
  getPage(page.value, {});
};

const handleProgress = (event, file, fileList) => {
  console.log('handleProgress', event);
  // let uploadProgress = file.percentage.toFixed(0)
  // this.uploadProgress = uploadProgress
};

const handleSuccess = (response, file, fileList) => {
  console.log('handleSuccess response', response);
  console.log('handleSuccess file', file);
  console.log('handleSuccess fileList', fileList);
  addMaterial({
    type: '1',
    groupId: groupId.value !== '-1' ? groupId.value : null,
    name: file.name,
    url: response.data.fileName
  }).then(() => {
    resultNumber.value++;
    if (fileList.length === resultNumber.value) {
      getPage(page.value, {});
      resultNumber.value = 0;
    }
  });
};
const beforeUpload = (file) => {
  const isPic =
    file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'video/mp4' || file.type === 'image/jpg';
  const isLt2M = file.size / 1024 / 1024 < 30;
  if (!isPic) {
    proxy?.$modal.msgError('上传图片只能是 JPG、JPEG、PNG、GIF 格式, 视频只能是  MP4格式!');
    return false;
  }
  if (!isLt2M) {
    proxy?.$modal.msgError('上传头像图片大小不能超过 2MB!');
  }
  return isPic && isLt2M;
};

const handleCheckedChange = (value) => {
  console.log('handleCheckedChange', value);
  pickItem.value = value;
};
/**
 *  确认选中图片
 */
const sureUrls = () => {
  console.log('this.urls:', urls.value[0]);
  myValue.value = urls.value[0].imgUrl;
  console.log('sureUrls pickItem', pickItem);
  // this.$emit('handleChecked', pickItem);
  emit('handleChecked', pickItem);
  listDialogVisible.value = false;
};

watch(
  () => props.imgList,
  async (val) => {
    console.log('imgList val', val);
    if (val) {
      pickItem.value = val;
    }
  },
  { deep: true, immediate: true }
);

onMounted(() => {
  materialGroupPage(); // 初始化列表数据
});
</script>

<style lang="scss" scoped>
.el-icon-circle-close {
  color: red;
}
.material-name {
  padding: 8px 0px;
}
.col-do {
  text-align: center;
}
.button-do {
  padding: unset !important;
  font-size: 12px;
}
</style>
